/*
 * @lc app=leetcode.cn id=32 lang=java
 *
 * [32] 最长有效括号
 */

// @lc code=start

import java.util.Stack;

class Solution {
    public int longestValidParentheses(String s) {
        if(s == null || s.length() == 0) {
            return 0;
        }
        Stack<Integer> stack = new Stack<>();

        int count = 0, left = -1;

        for(int i = 0; i < s.length(); i++) {
            if(s.charAt(i) == '(') {
                stack.push(i);
            } else {
                if(!stack.isEmpty()) {
                    stack.pop();
                    if(!stack.isEmpty()) {
                        count = Math.max(count, i - stack.peek());
                    } else {
                        count = Math.max(count, i - left);
                    }
                } else {
                    left = i;
                }
            }
        }
        return count;
    }
}
// @lc code=end

